<template>
  <div class="fillcontain" style="padding: 25px 15px 15px;">
    <div style="display:flex; min-height: 700px;">
      <asstnt-stndrd-items @queryStandItemTableData="queryStandItemTableData" ref="projectLibrary"
        itmeRootName="health">
      </asstnt-stndrd-items>
      <div class="right_box">
        <div class="right-title">健康建议规则</div>
        <!-- 健康建议规则列表 -->
        <div style="margin-left:40px ; margin-top: 25px;">
          <!-- 新增按钮 -->
          <!-- <el-button type="danger" size="mini" style="margin-left: 10px" plain @click="importExcel()"
            :loading="importLoading">导出Excel</el-button> -->
          <el-button type="danger" @click="handleAdd">新增</el-button>
          <el-button type="danger" @click="standPropertySaveClick">保存</el-button>
          <el-table :data="tableData.slice((page.pageIndex - 1) * page.pageSize, page.pageIndex * page.pageSize)"
            style="width: 100% ; margin-top: 15px;" ref="table" highlight-current-row>
            <el-table-column label="体检等级" min-width="80">
              <template slot-scope="scope">
                <el-select @change="gradedContentChange(scope.row)" v-model="scope.row.gradedContent" placeholder="请选择"
                  filterable clearable>
                  <el-option v-for="item in commonPropertyOpts" :key="item.id" :label="item.propertyType" :value="item.id + ''">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="健康建议" min-width="200">
              <template slot-scope="scope">
                <!-- <el-input style="width: 480px;" v-model="scope.row.healthAdvice" placeholder="请输入"></el-input> -->
                <div style="float: left; overflow:hidden">{{ scope.row.healthAdvice }}&nbsp; &nbsp;</div>
                <div style="float: left; margin-left: 10px;" class="handle-btn"
                  @click="addProject(scope.$index, scope.row)"> ...</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="80" align="center">
              <template slot-scope="scope">
                <span class="handle-btn" @click="handleAdd(scope.$index, scope.row)">新增</span>
                <span class="handle-btn" @click="handleDel(scope.$index, scope.row)">删除</span>
                <span class="handle-btn" @click="handleCopy(scope.$index, scope.row)">复制</span>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row>
            <el-col :span="24">
              <div class="pagination">
                <!-- 分页 -->
                <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                  :current-page="page.pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="page.pageSize"
                  :total="tableData.length" layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <el-dialog title="健康建议" :visible.sync="addProjectVisible" v-if="addProjectVisible" :show-close="false"
      :close-on-click-modal="false" width="60%" center>
      <el-form ref="healthForm" :model="healthForm" label-width="100px" :rules="projectRules" style="overflow: hidden;">
        <el-row>
          <el-col :span="20" class="common-box">
            <el-form-item label="健康建议：" prop="healthAdvice">
              <el-input maxlength="1990" type="textarea" :rows="10" placeholder="请输入内容" v-model="healthForm.healthAdvice">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="stndrdItemSave">保 存</el-button>
        <el-button @click="projectReset">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOwnDictProjectApi } from "@/api/medicalLibrary/examProjectLibrary";
import { getItemspropertiesApi } from "@/api/medicalLibrary/underwritingRule";
import { getAdviceRuleListApi, saveHealthAdvRuleApi, delHealthAdvRuleApi, exportHealthAdvRuleApi } from "@/api/medicalLibrary/healthAdviceRule";
import { getCommonInfoApi } from "@/api/medicalLibrary/medicalbank";
import constant from "@/utils/constant";

import asstntStndrdItems from '../../../../common/asstntStndrdItems.vue';


export default {
  components: {
    asstntStndrdItems,
  },
  data() {
    return {
      diseaseRuleDic: [],
      // 点击保存、导入按钮时显示加载中
      importLoading: false,
      healthIndex: '',
      healthRow: {},
      commonProperty: "",//健康建议规则体检项配置id
      // 体检项目库数据
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //    子项表格
      tableData: [],
      // 分页
      page: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      },
      currentRow: {},

      // 添加项目弹窗
      addProjectVisible: false,
      healthForm: {
        healthAdvice: '',
      },
      projectRules: {
        healthAdvice: [
          { required: true, message: '健康建议不能为空！', trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    // this.getOwnDictProjectList()
  },
  methods: {
    gradedContentChange(row) {
      this.$set(row, 'healthAdvice', '')
    },
    //体检等级
    getOwnDictProjectList() {
      getOwnDictProjectApi({ code: 'tirads' }).then(res => {
        if (res.resultCode == constant.SUCCESS) {
          this.diseaseRuleDic = res.data || []
          this.diseaseRuleDic.forEach(item => {
            item.value = item.remark
            item.label = item.dictValue
          })
        }
      })
    },
    // 导出execl
    importExcel() {
      this.importLoading = true
      exportHealthAdvRuleApi({ itemsCode: this.commonProperty, versionCode: this.versionId }).then(res => {
        this.importLoading = false
        let disposition = res.headers['content-disposition'],
          filename = decodeURI(disposition.split(';')[1].split('=')[1]).replace(/^(\s|")+|(\s|")+$/g, '')
        filename = filename.split('+-+')[1]
        let blob = new Blob([res.data], { type: `${res.data.type};charset=utf-8` })
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, filename);
        }
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = filename; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      }).catch(err => {
        this.importLoading = false
      });
    },
    /* ----列表操作按钮 */
    // 添加
    handleAdd(index, row) {
      if(this.commonProperty == undefined || this.commonProperty =='' || this.commonProperty == null){
          this.$message.closeAll()
            this.$message.warning('请选择体检项目!')
            throw new Error('')
      }
      let obj = {
        itemsCode: '',
        gradedContent: '',
        healthAdvice: '',
      }
      this.tableData.push(obj)
    },
    // 删除
    handleDel(index, row) {
      this.tableData.splice(index, 1)
    },
    // 复制
    handleCopy(index, row) {
      let obj = JSON.parse(JSON.stringify(row))
      delete obj.id
      delete obj.hitMark
      this.tableData.push(obj)
    },
    // 点击添加项目按钮
    addProject(index, row) {
      this.healthIndex = index;
      this.healthRow = row;
      this.healthForm.healthAdvice = row.healthAdvice;
      this.addProjectVisible = true
    },
    queryStandItemTableData(id, itemsCode, isLock, currentRow) {
      this.commonProperty = itemsCode;
      this.currentRow = currentRow;
      this.page = {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      }
      this.tableData = []
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      let params = {
        id: id,
        flag: 1,
      }
      getItemspropertiesApi(params).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          if(res.data != [] && res.data.length > 0){
            var propertyId = res.data[0].propertyId
            getCommonInfoApi({ id: propertyId }).then((res) => {
            if (res.resultCode === 0) {
              this.commonPropertyOpts = res.data && res.data.length ? res.data : [{ propertyType: '' }]
              this.getListData(this.commonProperty);
            }
          }).catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
          }else{
            this.getListData(this.commonProperty);
          }
        }
      })

    },
    getListData(itemsCode) {
      getAdviceRuleListApi({ itemsCode: itemsCode }).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.tableData = res.data || []
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
    },
    // 页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.pageIndex = 1;
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.pageIndex = val;
    },
    // 点击子项目列表删除按钮
    handleDel(_index, row) {
      this.$confirm(`是否删除此子项目信息?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.id) {
            this.$store.dispatch("loading/CHANGE_LOADING", true);
            delHealthAdvRuleApi({ id: row.id }).then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.resultCode == constant.SUCCESS) {
                let currentIndex = (this.page.pageIndex - 1) * (this.page.pageSize) + _index
                this.tableData.splice(currentIndex, 1);
                let pageTotal = (this.page.pageIndex - 1) * this.page.pageSize
                if (this.page.pageIndex != 1 && pageTotal >= this.tableData.length) this.page.pageIndex = this.page.pageIndex - 1
                this.$message.closeAll()
                this.$message.success('删除成功')
              }
            })
              .catch((err) => {
                this.$store.dispatch("loading/CHANGE_LOADING", false);
              });
          } else {
            let currentIndex = (this.page.pageIndex - 1) * (this.page.pageSize) + _index
            this.tableData.splice(currentIndex, 1);
            let pageTotal = (this.page.pageIndex - 1) * this.page.pageSize
            if (this.page.pageIndex != 1 && pageTotal >= this.tableData.length) this.page.pageIndex = this.page.pageIndex - 1
            this.$message.closeAll()
            this.$message.success('删除成功')
          }
        })
        .catch(() => { })
    },
    // 点击子项目新增按钮
    sonAddClick() {
      this.tableData.push({
        gradedContent: '',
        healthAdvice: '',
      })
    },
    // 点击子项目保存接口
    standPropertySaveClick() {
      if(this.commonProperty == undefined || this.commonProperty =='' || this.commonProperty == null){
          this.$message.closeAll()
            this.$message.warning('请选择体检项目!')
            throw new Error('')
      }
      try {
        this.tableData.forEach(item => {
          if (!item.gradedContent) {
            this.$message.closeAll()
            this.$message.warning('体检等级不能为空!')
            throw new Error('')
          }
          if (!item.healthAdvice) {
            this.$message.closeAll()
            this.$message.warning('健康建议不能为空!')
            throw new Error('')
          }
        })
      } catch (error) {
        return
      }
      this.saveStandardAttributesInfo()
    },
    saveStandardAttributesInfo() {
      let params = {
        itemsCode: this.commonProperty,
        adviceRuleList: this.tableData
      }
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveHealthAdvRuleApi(params).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.$message.closeAll()
          this.$message.success('保存成功')
          this.getListData(this.commonProperty)
          this.$refs.projectLibrary.currentId = null
          this.$refs.projectLibrary.filterText = ''
          this.$refs.projectLibrary.getProjectLibraryList(numbers.indexOf(this.commonProperty))
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
    },
    // 弹窗按钮
    // 点击确认
    stndrdItemSave() {
      this.$refs.healthForm.validate((valid) => {
        if (valid) {
          this.tableData[this.healthIndex].healthAdvice = this.healthForm.healthAdvice;
          this.addProjectVisible = false
          this.healthForm.healthAdvice = '';
        }
      });
    },
    // 点击取消
    projectReset() {
      this.addProjectVisible = false
      this.healthForm = {
        healthAdvice: '',
      }
    }
  },
}

</script>

<style lang="less" scoped>
.handle-btn {
  cursor: pointer;
  color: #409eff;
  display: inline-block;
  padding: 0 8px;
}

.right-title {
  background: #f8f8f8;
  padding: 10px 25px;
  margin-left: 15px;
  position: relative;
}

.right-title::before {
  content: '';
  position: absolute;
  top: 11px;
  left: 15px;
  width: 3px;
  height: 18px;
  background: #f76767;
}

.top_box {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid rgb(241, 238, 238);
  margin-bottom: 15px;
}

.top_box h1 {
  font-weight: 600;
  margin-left: 15px;
}

.left_box {
  width: 400px;
  border: 1px solid #e3dddd;
}

.right_box {
  width: calc(100% - 350px);
  /* border: 1px solid #e3dddd; */
}

/deep/ .filter-tree {
  max-height: calc(100vh - 340px);
  overflow: auto;
}
</style>